//
//  KDNewDayController.m
//  KongDays
//
//  Created by deeplu on 12. 12. 20..
//  Copyright (c) 2012년 BlueBeans. All rights reserved.
//

#import "KDNewDayController.h"
#import "KDDayListController.h"
#import "KDRepeatController.h"
#import "KDMemoController.h"
#import "KDAlarmController.h"
#import "KDAppDelegate.h"
#import "NSDay.h"
#import "KDDayType.h"
#import "KDRepeat.h"

#define kDayTitleTextFieldTag   100
#define kDateTextLabelTag       101
#define kRepeatTextLabelTag     102
#define kAlarmTextLabelTag      103
#define kMemoTextLabelTag       104

@interface KDNewDayController ()

- (void)initDatePickerWithActionsheet;
- (void)showDatePicker;
- (void)selectDate;
- (void)closeDatePicker;

- (void)initNavigationBar;
- (UITextField *)dayTitleTextField;
- (UILabel *)dateLabel;
- (UILabel *)repeatLabel;
- (UILabel *)memoLabel;
- (NSString *)dateToString:(NSDate *)date;
- (void)pushRepeatsController;
- (void)pushMemoController;
- (void)pushAlarmController;
- (void)textFieldDidChange:(UITextField *)textField;

@end

@implementation KDNewDayController
@synthesize dayToEdit;
@synthesize fieldTable;

- (id)init
{
    self = [super initWithNibName:@"KDNewDayController" bundle:nil];
    if (self) {

    }
    
    return (self);
}

- (void)dealloc
{
    [actionSheet release];
    [datePicker release];
    [dayToEdit release];
    
    [dayTitle_ release];
    [date_ release];
    [repeat_ release];
    [memo_ release];
    
    [fieldTable release];
    
    [super dealloc];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    isFirstLoaded = YES;
    isShowingDetails = NO;
    
    [self initNavigationBar];
    [self initDatePickerWithActionsheet];
    
    self.title = NSLocalizedString(@"KDNewDayController Title", nil);
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    [self.fieldTable setSectionHeaderHeight:0.0f];
    [self.fieldTable setSectionFooterHeight:0.0f];
    
    if (self.dayToEdit) {
        self.dayTitle = self.dayToEdit.title;
        self.date = self.dayToEdit.date;
    } else {
        self.date = [NSDate date];
        self.repeat = [[KDRepeat all] objectAtIndex:2];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (isFirstLoaded && self.dayToEdit == nil) {
        
        /*
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.1f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        
        [self.fieldTable setContentOffset:CGPointMake(0.0, 200.0)];
        
        [UIView commitAnimations];
        */
        
        [[self dayTitleTextField] becomeFirstResponder];
        isFirstLoaded = NO;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Properties

- (NSString *)dayTitle
{
    return dayTitle_;
}

- (void)setDayTitle:(NSString *)dayTitle
{
    if (dayTitle_ != dayTitle) {
        [dayTitle_ release];
        dayTitle_ = [dayTitle copy];
    }
}

- (NSDate *)date { return date_; }

- (void)setDate:(NSDate *)date
{
    if (date_ != date) {
        [date_ release];
        date_ = [date retain];
        
        [self dateLabel].text = [self dateToString:self.date];
    }
}

- (KDRepeat *)repeat { return repeat_; }

- (void)setRepeat:(KDRepeat *)repeat
{
    if (repeat_ != repeat) {
        [repeat_ release];
        repeat_ = [repeat retain];
        
        [self repeatLabel].text = self.repeat.displayText;
     
    }
}

- (NSString *)memo { return memo_; }

- (void)setMemo:(NSString *)memo
{
    if (memo_ != memo) {
        [memo_ release];
        memo_ = [memo copy];
        
        [self memoLabel].text = self.memo;
    }
}

#pragma mark - IBAction methods

- (IBAction)add:(id)sender
{
    KDAppDelegate *delegate = [KDAppDelegate sharedAppDelegate];
    
    NSDay *newDay = [NSEntityDescription
                     insertNewObjectForEntityForName:@"KDDay"
                     inManagedObjectContext:delegate.managedObjectContext];
    
    if (newDay != nil)
    {
        newDay.title = self.dayTitle;
        newDay.date = self.date;
        newDay.repeat = self.repeat.value;
        newDay.memo = self.memo;
        
        NSError *error = nil;
        if ([delegate.managedObjectContext save:&error] == YES) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            // 저장 실패
        }
    } else {
        // 객체 생성 실패
    }
}

#pragma mark - UITableViewDelegate methods

-       (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[self dayTitleTextField] resignFirstResponder];
    
    if (indexPath.section == 1) {
        
        switch (indexPath.row) {
            case 0:
                [[self dayTitleTextField] becomeFirstResponder];
                break;
            case 1:
                [self showDatePicker];                
                break;
            case 2:
                [self pushRepeatsController];
                break;
            case 3:
                if (isShowingDetails) {
                    [self pushAlarmController];
                } else {
                    
                    isShowingDetails = YES;
                    
                    [self.fieldTable reloadSections:[NSIndexSet indexSetWithIndex:1]
                                   withRowAnimation:UITableViewRowAnimationFade];
                }
                break;
            case 4:
                [self pushMemoController];
                break;
        }
    }
    
    [self.fieldTable deselectRowAtIndexPath:indexPath animated:YES];
}

-       (CGFloat)tableView:(UITableView *)tableView
  heightForHeaderInSection:(NSInteger)section
{
    return 10.0f;
}

-       (CGFloat)tableView:(UITableView *)tableView
  heightForFooterInSection:(NSInteger)section
{
    return 0.0f;
}

-       (CGFloat)tableView:(UITableView *)tableView
   heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
    if (indexPath.section == 0)
        return 200.0f;
    else
        return [self.fieldTable rowHeight];
    */
    return [self.fieldTable rowHeight];
}

#pragma mark - UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section;
{
    if (section == 0)
        return 0;
    else {
        if (isShowingDetails)
            return 5;
        else
            return 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    int section = [indexPath section];
    int row = [indexPath row];
    
    UIFont *defaultFont = [UIFont fontWithName:@"Helvetica" size:14.0f];
    
    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier]
                autorelease];
    
        cell.selectedBackgroundView = nil;
        cell.textLabel.textColor = [UIColor lightGrayColor];
        cell.textLabel.font = defaultFont;
        
        if (section == 0) {
            
            // 기념일 관련 사진
            
        } else if (section == 1) {
            
            if (row == 0) {
                
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                UITextField *titleField = [[[UITextField alloc] initWithFrame:CGRectMake(10.0, 13.0, 200.0, 25.0)] autorelease];
                titleField.tag = kDayTitleTextFieldTag;
                titleField.font = defaultFont;
                titleField.delegate = self;
                titleField.placeholder = NSLocalizedString(@"Title Placeholder", nil);
                [titleField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
                titleField.text = self.dayTitle;
                [cell.contentView addSubview:titleField];
                
            } else if (row == 1) {
                
                cell.textLabel.text = NSLocalizedString(@"Date", nil);
                
                UILabel *dateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(80.0, 15.0, 200.0, 14.0)] autorelease];
                dateLabel.textAlignment = UITextAlignmentLeft;
                dateLabel.backgroundColor = [UIColor clearColor];
                dateLabel.font = defaultFont;
                dateLabel.tag = kDateTextLabelTag;
                dateLabel.text = [self dateToString:self.date];
                                
                [cell.contentView addSubview:dateLabel];
                
            } else if (row == 2) {
                
                cell.textLabel.text = NSLocalizedString(@"Repeat", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
                UILabel *repeatsLabel = [[[UILabel alloc] initWithFrame:CGRectMake(80.0, 12.0, 200.0, 20.0)] autorelease];
                repeatsLabel.textAlignment = UITextAlignmentLeft;
                repeatsLabel.backgroundColor = [UIColor clearColor];
                repeatsLabel.font = defaultFont;
                repeatsLabel.tag = kRepeatTextLabelTag;
                repeatsLabel.text = self.repeat.displayText;
                
                [cell.contentView addSubview:repeatsLabel];
                
            } else if (row == 3) {
                
                if (isShowingDetails) {
                    
                    cell.textLabel.text = NSLocalizedString(@"Alarm", nil);
                    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                    
                    UILabel *notiLabel =
                    [[[UILabel alloc] initWithFrame:
                      CGRectMake(80.0, 12.0, 195.0, 20.0)] autorelease];
                    notiLabel.textAlignment = UITextAlignmentLeft;
                    notiLabel.backgroundColor = [UIColor clearColor];
                    notiLabel.font = defaultFont;
                    notiLabel.tag = kAlarmTextLabelTag;
                    notiLabel.text = NSLocalizedString(@"Off", nil);
                    
                    [cell.contentView addSubview:notiLabel];
                    
                } else {
                    
                    UILabel *text = [[[UILabel alloc]
                                      initWithFrame:CGRectMake(10.0, 10.0, 280.0, 25.0)] autorelease];
                    text.backgroundColor = [UIColor clearColor];
                    text.font = [UIFont boldSystemFontOfSize:12.0];
                    text.textAlignment = NSTextAlignmentCenter;
                    text.textColor = [UIColor grayColor];
                    text.text = NSLocalizedString(@"Show Details", nil);
                    
                    [cell.contentView addSubview:text];
                    
                }
                
            } else if (row == 4) {
                
                cell.textLabel.text = NSLocalizedString(@"Memo", nil);
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                UILabel *memoLabel =
                [[[UILabel alloc] initWithFrame:
                  CGRectMake(80.0, 12.0, 195.0, 20.0)] autorelease];
                memoLabel.textAlignment = UITextAlignmentLeft;
                memoLabel.backgroundColor = [UIColor clearColor];
                memoLabel.font = defaultFont;
                memoLabel.tag = kMemoTextLabelTag;
                memoLabel.text = self.memo;
                
                [cell.contentView addSubview:memoLabel];
            }
            
        }
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

#pragma mark - UITextFieldDelegate methods

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    /*
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    
    [self.fieldTable setContentOffset:CGPointMake(0.0, 205.0)];
    
    [UIView commitAnimations];
     */
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - KDRepeatsControllerDelegate methods

- (void)repeatDidChange:(KDRepeat *)repeat
{
    self.repeat = repeat;
    
    [self dateLabel].text = [self dateToString:self.date];
}

#pragma mark - KDMemoControllerDelegate methods

- (void)memoDidChange:(NSString *)memo
{
    self.memo = memo;
}

#pragma mark - KDAlarmControllerDelegate

- (void)alarmDidChange
{
    
}

#pragma mark - Private methods

- (void)initDatePickerWithActionsheet
{    
    actionSheet =
        [[UIActionSheet alloc] initWithTitle:nil
                                    delegate:self
                           cancelButtonTitle:nil
                      destructiveButtonTitle:nil
                           otherButtonTitles:nil, nil];
    
    NSMutableArray *items = [[NSMutableArray alloc] init];
    
    
    
    UIBarButtonItem *flexibleSpace =
        [[UIBarButtonItem alloc]
         initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
         target:nil
         action:nil];
    
    [items addObject:flexibleSpace];
    [flexibleSpace release];
    
    UIBarButtonItem *cancelButton =
    [[UIBarButtonItem alloc]
     initWithTitle:NSLocalizedString(@"Cancel", nil)
     style:UIBarButtonItemStyleBordered
     target:self
     action:@selector(closeDatePicker)];

    [items addObject:cancelButton];
    [cancelButton release];
    
    UIBarButtonItem *doneButton =
        [[UIBarButtonItem alloc]
          initWithTitle:NSLocalizedString(@"Done", nil)
          style:UIBarButtonItemStyleDone
          target:self
         action:@selector(selectDate)];
    
    [items addObject:doneButton];
    [doneButton release];
    
    UIToolbar *pickerToolbar =
        [[UIToolbar alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
    
    [pickerToolbar setItems:items];
    [items release];
    
    datePicker =
        [[UIDatePicker alloc]
         initWithFrame:CGRectMake(0.0, 44.0, 320.0, 216.0)];
    
    [datePicker addTarget:self
                   action:@selector(dateDidChange)
         forControlEvents:UIControlEventValueChanged];
    
    datePicker.datePickerMode = UIDatePickerModeDate;
    
    [actionSheet addSubview:pickerToolbar];
    [pickerToolbar release];
    
    [actionSheet addSubview:datePicker];
}

- (void)showDatePicker
{
    [actionSheet showInView:self.view];
    [actionSheet setBounds:CGRectMake(0.0, 0.0, 320.0, 500.0)];
}

- (void)closeDatePicker
{
    [self dateLabel].text = [self dateToString:self.date];
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)selectDate
{
    self.date = datePicker.date;
    
    [self dateLabel].text = [self dateToString:self.date];
    
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)dateDidChange
{
    [self dateLabel].text = [self dateToString:datePicker.date];
}

- (void)initNavigationBar
{
    UIBarButtonItem *addButton = [[[UIBarButtonItem alloc]
                                   initWithTitle:NSLocalizedString(@"Add", nil)
                                   style:UIBarButtonItemStyleDone
                                   target:self
                                   action:@selector(add:)] autorelease];
    
    self.navigationItem.rightBarButtonItem = addButton;
}

- (UITextField *)dayTitleTextField
{
    UITableViewCell *titleCell = [self.fieldTable
                                  cellForRowAtIndexPath:
                                  [NSIndexPath indexPathForRow:0 inSection:1]];
    
    return (UITextField *)[titleCell viewWithTag:kDayTitleTextFieldTag];
}

- (UILabel *)dateLabel
{
    UITableViewCell *cell = [self.fieldTable cellForRowAtIndexPath:
                             [NSIndexPath indexPathForRow:1 inSection:1]];
    
    return (UILabel *)[cell viewWithTag:kDateTextLabelTag];
}

- (UILabel *)repeatLabel
{
    UITableViewCell *repeatCell = [self.fieldTable cellForRowAtIndexPath:
                                   [NSIndexPath indexPathForRow:2 inSection:1]];
    
    return (UILabel *)[repeatCell viewWithTag:kRepeatTextLabelTag];
}

- (UILabel *)memoLabel
{
    UITableViewCell *cell = [self.fieldTable cellForRowAtIndexPath:
                             [NSIndexPath indexPathForRow:4 inSection:1]];
    
    UILabel *label = (UILabel *)[cell viewWithTag:kMemoTextLabelTag];
    
    return label;
}

- (NSString *)dateToString:(NSDate *)aDate
{
    NSString *repeatValue = self.repeat.value;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    
    if ([repeatValue isEqualToString:@"month"]) {
        [dateFormat setDateFormat:NSLocalizedString(@"Every Month Date Format", nil)];
    } else if ([repeatValue isEqualToString:@"year"]) {
        [dateFormat setDateFormat:NSLocalizedString(@"Every Year Date Format", nil)];
    } else {
        [dateFormat setDateFormat:NSLocalizedString(@"Short Date Format", nil)];
    }
    
    NSString *displayText = [dateFormat stringFromDate:aDate];
    
    [dateFormat release];
    
    return displayText;
}

- (void)pushRepeatsController
{
    KDRepeatController *repeatsController = [[[KDRepeatController alloc] init]
                                              autorelease];
    repeatsController.delegate = self;
    repeatsController.defaultRepeat = self.repeat;
    
    [self.navigationController pushViewController:repeatsController
                                         animated:YES];
}

- (void)pushMemoController
{
    KDMemoController *memoController =[[[KDMemoController alloc] init]
                                       autorelease];
    memoController.memo = self.memo;
    memoController.delegate = self;
    
    [self.navigationController pushViewController:memoController
                                         animated:YES];
}

- (void)pushAlarmController
{
    KDAlarmController *alarmController = [[[KDAlarmController alloc] init]
                                          autorelease];
    
    alarmController.delegate = self;
    
    [self.navigationController pushViewController:alarmController animated:YES];
}

- (void)textFieldDidChange:(UITextField *)textField
{
    self.dayTitle = textField.text;
    
    BOOL enabled = NO;
    if (self.dayTitle.length > 0)
        enabled = YES;

    self.navigationItem.rightBarButtonItem.enabled = enabled;
}

@end
